//
//  placeService.swift
//  placepic
//
//  Created by 이유진 on 2020/07/08.
//  Copyright © 2020 elesahich. All rights reserved.
//

import Foundation
import Alamofire

protocol PlaceListInterface {
    func getAllPlaces (_ categoryIdx: Int, _ tag: [Int], _ subway: [Int], completion: @escaping (placeListClass?)-> Void)
    func getPlaces(_ categoryIdx: Int, _ tag: [Int], _ subway: [Int], completion: @escaping (placeListClass?)-> Void)
    func getSelectedPlaces(_ categoryIdx: Int, completion: @escaping (placeListClass?)-> Void)
}

class placeService: PlaceListInterface {
    
    static let shared = placeService()
    
    func getSelectedPlaces(_ categoryIdx: Int, completion: @escaping (placeListClass?) -> Void) {
        
        let defaults = UserDefaults.standard
        guard
            let keyword = defaults.array(forKey: "keyword") as? [Int],
            let useful = defaults.array(forKey: "useful") as? [Int],
            let subway = defaults.array(forKey: "subway") as? [Int],
            let token = defaults.string(forKey: "accessToken")
            else {
                return
        }
        
        // keyword, useful
        var tag = ""
        var intArray: [Int] = []
        intArray.append(contentsOf: keyword)
        intArray.append(contentsOf: useful)
        tag = intArray
            .reduce("") { $0 + "," + String($1) }
            .trimmingCharacters(in: [","])
        
        // subway
        let subwayparam = subway
            .reduce("") { $0 + "," + String($1) }
            .trimmingCharacters(in: [","])
        
        // URLComponet
        let defaultquery = "?sort=desc&categoryIdx=\(categoryIdx)&tagIdx=\(tag)&subwayIdx=\(subwayparam)"
        guard let receivedURL = URL(string: placeListAPI.getplacedURL + defaultquery) else { return }
       
        var componentURL = URLComponents(url: receivedURL, resolvingAgainstBaseURL: false)
        let emptyQuery = URLQueryItem(name: "", value: "")
        // 세가지 필터링 검사이후 없으면 emptyQuery 넣기
        if categoryIdx == 0 {
            componentURL?.queryItems?[1] = emptyQuery
        }
        if subway == [] {
            componentURL?.queryItems?[3] = emptyQuery
        }
        if tag == "" {
            componentURL?.queryItems?[2] = emptyQuery
        }
        
        // url 만들기
        guard let url = componentURL?.url else { return }
        let header: HTTPHeaders = [
            "token": token,
            "Content-Type": "application/json"
        ]
        
        
        
        Alamofire.request(url,
                          method: .get,
                          parameters: .none,
                          encoding: JSONEncoding.default,
                          headers: header).responseJSON { response in
                            
                            switch response.result {
                            case .success:
//                                print("request:: \(response.request)")

                                guard let data = response.data else { return }
                                do {
                                    let decoder = JSONDecoder()
                                    let object = try decoder.decode(TempResponseResult<placeListClass>.self, from: data)
                                    if object.success {
                                        completion(object.data)
                                    } else {
                                        completion(nil)
                                    }
                                } catch (let err) {
                                    print(err.localizedDescription)
                                }
                            case .failure:
                                completion(nil)
                            }
        }
    }
    
    func getPlaces(_ categoryIdx: Int, _ tag: [Int], _ subway: [Int], completion: @escaping (placeListClass?)-> Void) {
        
        let emptyQuery = URLQueryItem(name: "", value: "")
        let defaultquery = "?sort=desc&categoryIdx=\(categoryIdx)&tagIdx=\(tag)&subwayIdx=\(subway)"
        
        guard
            let token = UserDefaults.standard.string(forKey: "accessToken"),
            let receivedURL = URL(string: placeListAPI.getplacedURL + defaultquery)
            else { return }
        
        var componentURL = URLComponents(url: receivedURL, resolvingAgainstBaseURL: false) // 얘는 걍 무조건 있는애잖아
        
        if subway == [] {
            componentURL?.queryItems?[2] = emptyQuery
        }
        if tag == [] {
            componentURL?.queryItems?[3] = emptyQuery
        }
        
        let header: HTTPHeaders = [
            "token": token,
            "Content-Type": "application/json"
        ]
        
        guard let url = componentURL?.url else { return }
        Alamofire.request(url,
                          method: .get,
                          parameters: .none,
                          encoding: JSONEncoding.default,
                          headers: header).responseJSON { response in
                            
//                            print("request:: \(response.request)")
                            switch response.result {
                            case .success:
                                
                                guard let data = response.data else { return }
                                do {
                                    let decoder = JSONDecoder()
                                    let object = try decoder.decode(TempResponseResult<placeListClass>.self, from: data)
                                    if object.success {
                                        completion(object.data)
                                    } else {
                                        completion(nil)
                                    }
                                } catch (let err) {
                                    print(err.localizedDescription)
                                }
                                
                            case .failure:
                                completion(nil)
                            }
        }
    }
    
    func getAllPlaces (_ categoryIdx: Int, _ tag: [Int], _ subway: [Int], completion: @escaping (placeListClass?)-> Void) {
        let emptyQuery = URLQueryItem(name: "", value: "")
        let defaultquery = "?sort=desc&tagIdx=\(tag)&subwayIdx=\(subway)"
        
        guard
            let token = UserDefaults.standard.string(forKey: "accessToken"),
            let receivedURL = URL(string: placeListAPI.getplacedURL + defaultquery)
            else { return }
        
        var componentURL = URLComponents(url: receivedURL, resolvingAgainstBaseURL: false)
        
        if subway == [] {
            componentURL?.queryItems?[1] = emptyQuery
        }
        if tag == [] {
            componentURL?.queryItems?[2] = emptyQuery
        }
        
        let header: HTTPHeaders = [
            "token": token,
            "Content-Type": "application/json"
        ]
        guard let url = componentURL?.url else { return }
        Alamofire.request(url,
                          method: .get,
                          parameters: .none,
                          encoding: JSONEncoding.default,
                          headers: header).responseJSON { response in
//                            print("request:: \(response.request)")
                            switch response.result {
                            case .success:
                                guard let data = response.data else { return }
                                do {
                                    let decoder = JSONDecoder()
                                    let object = try decoder.decode(TempResponseResult<placeListClass>.self, from: data)
                                    if object.success {
                                        completion(object.data)
                                    } else {
                                        completion(nil)
                                    }
                                } catch (let err) {
                                    print(err.localizedDescription)
                                }
                                
                            case .failure:
                                completion(nil)
                            }
        }
    }
}

//    func getPlaces(_ queryurl: String,completion: @escaping (NetworkResult<Any>) -> Void) {
//        print(#function)
//        let url = placeListAPI.getplacedURL + queryurl
//        let header: HTTPHeaders = [
//            "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZHgiOjMsIm5hbWUiOiLstZzsmIHtm4giLCJpYXQiOjE1OTM2OTkxODMsImV4cCI6MTU5NjI5MTE4MywiaXNzIjoicGxhY2VwaWMifQ.rmFbeBfviyEzbMlMM4b3bMMiRcNDDbiX8bQtwL_cuN0",
//            "Content-Type": "application/json"
//        ]
//
//
//        Alamofire.request(url, method: .get, parameters: .none, encoding: JSONEncoding.default, headers: header).responseJSON { response in
//
//            switch response.result {
//            case .success:
//
//                guard let data = response.data else { return }
//                do {
//                    let decoder = JSONDecoder()
//                    let object = try decoder.decode(TempResponseResult<DataClass>.self, from: data)
//                    if object.success {
//                        completion(object.data)
//
//                    } else {
//                        completion(nil)
//                    }
//                } catch (let err) {
//                    print(err.localizedDescription)
//                }
//
//            case .failure:
//                completion(nil)
//            }
//
//
//
//        }
//}
//        let dataRequest = Alamofire.request(url, method: .get, encoding:JSONEncoding.default, headers: header)
//
//        dataRequest.responseData { dataResponse in
//            switch dataResponse.result {
//            case .success:
//                guard let statusCode = dataResponse.response?.statusCode else { return }
//                print(statusCode)
//                guard let value = dataResponse.result.value else { return }
//                let networkResult = self.judge(by: statusCode, value)
//                completion(networkResult)
//            case .failure:
//                completion(.networkFail)
//            }
//        }
//    }
//    private func judge(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {
//        switch statusCode {
//        case 200:
//            print("judge 200")
//            return isPlace(by: data)
//        case 400: return .pathErr
//        case 500: return .serverErr
//        default: return .networkFail
//        }
//    }
//
//    private func isPlace(by data: Data) -> NetworkResult<Any> {
//        let decoder = JSONDecoder()
//
//        guard let decodedData = try? decoder.decode(placeListModel.self, from: data) else { return .pathErr }
//        guard let placeData: placeListClass = decodedData.data else { return .requestErr(decodedData.message) }
//
//        return .success(placeData)
//    }

